package org.lab.curator;

import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.recipes.locks.InterProcessMutex;
import org.apache.curator.retry.ExponentialBackoffRetry;

import java.util.concurrent.TimeUnit;

/**
 * Created by lichengwen on 2017/2/4.
 */
public class CuratorTest {

  private static int aa = 0;

  public static void main(String[] args) {
    RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 3);
    CuratorFramework client = CuratorFrameworkFactory.newClient("127.0.0.1:2181", retryPolicy);
    client.start();

    final InterProcessMutex lock = new InterProcessMutex(client, "/locks");
    for (int i = 0; i < 10; i++) {
      new Thread("thread-" + i) {

        public void run() {
          while (true) {
            try {
              if (lock.acquire(1, TimeUnit.SECONDS)) {
                System.out.println(this.getName() + " fetched lock." + (++aa));
                lock.release();
              }
              TimeUnit.SECONDS.sleep(1);
            } catch (Exception e) {
              e.printStackTrace();
            }
          }
        }

      }.start();
    }

    try {
      Thread.sleep(10000);
    } catch (InterruptedException e) {
      e.printStackTrace();
    }
  }

}
